package com.int_tech.data.controller;

import com.int_tech.data.dao.DataInfoDao;
import com.int_tech.data.dao.HyjStatusDao;
import com.int_tech.data.entity.DataInfo;
import com.int_tech.data.entity.HyjStatus;
import com.int_tech.data.service.DataService;
import com.int_tech.shebeiManager.dao.ShebeiDao;
import com.int_tech.shebeiManager.entity.*;
import com.int_tech.utils.KuaYu;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

/**
 * Created by liubch on 2018/6/9.
 */
@Controller
@RequestMapping("/getData")
public class DataController {

    @Autowired
    private DataInfoDao dataInfoDao;

    @Autowired
    private DataService dataService;

    @Autowired
    private HyjStatusDao hyjStatusDao;

    @Autowired
    private ShebeiDao shebeiDao;


    /**
     * 通过车辆查询信息
     * @param request
     * @param response
     * @param shebeiId
     * @return
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/getDataByShebeiId", method = RequestMethod.POST,produces="application/json")
    public String getDataByShebeiId(HttpServletRequest request, HttpServletResponse response,String shebeiId) throws UnsupportedEncodingException {

        KuaYu.kuaYuResponse(response);


//        Page<DataInfo> dataInfoPage = dataService.findByShebeiId(1, 10,shebeiId);

        Page<DataInfo> dataInfoPage = dataService.findByShebeiIdAndZhenTouOrderByCreateTimeDesc(1, 10,shebeiId,"A1");


        List<DataInfo> dataInfoList = dataInfoPage.getContent();

        if(dataInfoList == null || dataInfoList.size() == 0)
        {
            JSONObject jsonObject = new JSONObject();

            jsonObject.put("noA1","没有找到匹配的测量数据");
            Shebei shebei = shebeiDao.findByShebeiId(shebeiId);

            jsonObject.put("wendufz",shebei.getWendufz());
            jsonObject.put("shidufz",shebei.getShidufz());
            jsonObject.put("xfz",shebei.getXfz());
            jsonObject.put("yfz",shebei.getYfz());
            jsonObject.put("zfz",shebei.getZfz());
            jsonObject.put("shebeiName",shebei.getShebeiName());
            String resultJson = jsonObject.toString();

            return resultJson;
        }

        DataInfo lastData = dataInfoList.get(0);


        JSONObject jsonObject = new JSONObject();

        String s1 = lastData.getDataString();


//        data = "A10030003E343647073636303031393830303130363039333433382E303030302E3030000000000000302E30000000000000000001061734002E00002E003050BA561501F7FFE6FF078300001000004706170000"


        //贞头
        String zhetou = s1.substring(0,2);

        //芯片id
        String id = s1.substring(2,26);

        //UTC时间
        String utcTime = s1.substring(26,62);

        String utcTimeNew = "";

        int m = 1;

        for(int i = 0 ;i < utcTime.length(); i++)
        {
            if(m == 5)
            {
                utcTimeNew += "-";
            }

            if(m == 7)
            {
                utcTimeNew += "-";
            }

            if(m == 9)
            {
                utcTimeNew += " ";
            }

            if(m == 11)
            {
                utcTimeNew += ":";
            }

            if(m == 13)
            {
                utcTimeNew += ":";
            }

            if(m > 14)
            {
                break;
            }

            if(i%2 == 0)
            {

            }
            else
            {
                utcTimeNew += utcTime.substring(i,i+1);

                m++;
            }
        }

        utcTimeNew = utcTimeNew.replaceAll("--","-");
        utcTimeNew = utcTimeNew.replaceAll("::",":");
        utcTimeNew = utcTimeNew.replaceAll("  "," ");




        //纬度
        String lng = s1.substring(62,82);
        String lngNew = "";

        for(int i = 0 ;i < lng.length(); i++)
        {
            if(i%2 == 0)
            {

            }
            else
            {
                lngNew += lng.substring(i,i+1);
            }
        }

        lngNew = lngNew.replace("E",".");



        //经度
        String lat = s1.substring(82,104);

        String latNew = "";

        for(int i = 0 ;i < lat.length(); i++)
        {
            if(i%2 == 0)
            {

            }
            else
            {
                latNew += lat.substring(i,i+1);
            }
        }

        latNew = latNew.replace("E",".");



        String url = "http://api.map.baidu.com/geoconv/v1/?coords="+latNew+","+lngNew+"&from=1&to=5&ak=TsCP2qXsP0RLmchQ7cQYyQa1C5Cwh4er";

        String result = this.getJson(url);

        JSONObject object = JSONObject.fromObject(result);

        JSONArray result1 = (JSONArray) object.get("result");

        object = result1.getJSONObject(0);

        latNew = String.valueOf((Double) object.get("x"));
        lngNew = String.valueOf((Double) object.get("y"));


        jsonObject.put("lng",lngNew);

        jsonObject.put("lat",latNew);

        //自定义时间
        String selfTime = s1.substring(104,112);

        //纬度短
        String lng1 = s1.substring(112,118);

        //经度短
        String lat1 = s1.substring(118,124);

        //湿度
        String wendu = s1.substring(126,128) + s1.substring(124,126);

        wendu = String.valueOf((Integer.parseInt(wendu,16)*0.00268127)-46.85);

        wendu = wendu.substring(0,wendu.lastIndexOf(".")+3);

        jsonObject.put("wendu",wendu);


        //湿度
        String shidu = s1.substring(130,132) + s1.substring(128,130);

        shidu = String.valueOf((Integer.parseInt(shidu,16)*0.00190735)-6);

        shidu = shidu.substring(0,shidu.lastIndexOf(".")+2)+"%";

        jsonObject.put("shidu",shidu);

        //振动
        String x = s1.substring(134,136) + s1.substring(132,134);

        String startx = s1.substring(134,136);

        if(startx.startsWith("0")||startx.startsWith("A"))
        {
            Integer x1 = Integer.parseInt(x,16);

            x = String.valueOf(x1*3.9);

            jsonObject.put("x",x.substring(0,x.lastIndexOf(".")+2));
        }
        else
        {
            //振动
            Integer x1 = Integer.parseInt("FFFF",16)-Integer.parseInt(x,16);

            x = String.valueOf(x1*3.9);

            jsonObject.put("x",x.substring(0,x.lastIndexOf(".")+2));
        }



//        x = x.substring(0,x.lastIndexOf(".")+3);

        String y = s1.substring(138,140) + s1.substring(136,138);

        String starty = s1.substring(138,140);

        if(starty.startsWith("0")||starty.startsWith("A"))
        {
            Integer y1 = Integer.parseInt(y,16);

            y = String.valueOf(y1*3.9);

            jsonObject.put("y",y.substring(0,y.lastIndexOf(".")+2));
        }
        else
        {
            Integer y1 = Integer.parseInt("FFFF",16)-Integer.parseInt(y,16);

            y = String.valueOf(y1*3.9);

            jsonObject.put("y",y.substring(0,y.lastIndexOf(".")+2));
        }



//        y = y.substring(0,y.lastIndexOf(".")+3);

        String z = s1.substring(142,144) + s1.substring(140,142);

        String start = s1.substring(142,144);

        if(start.startsWith("0")||start.startsWith("A"))
        {
            Integer z1 = Integer.parseInt(z,16);

            z = String.valueOf(z1*3.9);

//        z = z.substring(0,z.lastIndexOf(".")+3);

            jsonObject.put("z",z.substring(0,z.lastIndexOf(".")+2));
        }
        else
        {
            Integer z1 = Integer.parseInt("FFFF",16)-Integer.parseInt(z,16);

            z = String.valueOf(z1*3.9);

            jsonObject.put("z",z.substring(0,z.lastIndexOf(".")+2));
        }



        //氦压机状态
        String status = s1.substring(145,146);

        String hyjStatus = "";


        for(int i = 0;i < status.length();i ++)
        {
            int aaa = Integer.valueOf(status);

            String sss = Integer.toBinaryString(aaa);

            int q = sss.length();

            q = 4-q;

            String qianzhui = "";

            for(int zz = 0;zz < q;zz++)
            {
                hyjStatus += "0";
            }

            hyjStatus += sss;
        }


        String HYJdataToPage = "";
        for (int i = 0;i < 4;i++)
        {

            String key = "";
            if(i == 0)
            {
                key = "停机报警";
            }
            else if(i == 1)
            {
                key = "氦压机温度报警";
            }
            else if(i == 2)
            {
                key = "环境温度报警";
            }
            else if(i == 3)
            {
                key = "压力报警";
            }

            String shiStatus = hyjStatus.substring(i,i+1);

            HYJdataToPage += "<tr>";
            HYJdataToPage += "<td class='info_L'>"+key+"</td>";

            if(i == 0)
            {
                if("1".equals(shiStatus))
                {
                    HYJdataToPage += "<td class='info_R'>正常</td>";
                }
                else
                {
                    HYJdataToPage += "<td class='info_R' style='color:red;'>报警</td>";
                }
            }
            else
            {
                if("0".equals(shiStatus))
                {
                    HYJdataToPage += "<td class='info_R'>正常</td>";
                }
                else
                {
                    HYJdataToPage += "<td class='info_R' style='color:red;'>报警</td>";
                }
            }

            HYJdataToPage += "</tr>";

        }


        jsonObject.put("hyjStatus",HYJdataToPage);





        //发电机01功能码采集值
        String gongneng01 = s1.substring(146,156);

        String shiString = "";


        for(int i = 0;i < gongneng01.length();i ++)
        {
            int aaa = Integer.valueOf(gongneng01.substring(i,i+1));

            String sss = Integer.toBinaryString(aaa);

            int q = sss.length();

            q = 4-q;

            String qianzhui = "";

            for(int zz = 0;zz < q;zz++)
            {
                shiString += "0";
            }

            shiString += sss;
        }


        List<HyjStatus> hyjStatuses = hyjStatusDao.findAll();


        String dataToPage = "";
        for (int i = 0;i < hyjStatuses.size();i++)
        {
            if(hyjStatuses.get(i).getStatus() == 0)
            {
                continue;
            }
            String shiStatus = shiString.substring(i,i+1);

            dataToPage += "<tr>";
            dataToPage += "<td class='info_L'>"+hyjStatuses.get(i).getName()+"</td>";

            if("0".equals(shiStatus))
            {
                dataToPage += "<td class='info_R'>正常</td>";
            }
            else
            {
                dataToPage += "<td class='info_R' style='color:red;'>报警</td>";
            }

            dataToPage += "</tr>";

        }


        jsonObject.put("shiStatus",dataToPage);

        //发电机03功能码采集值
        String gongneng03 = s1.substring(156,168);

        String youwen = gongneng03.substring(0,4);

        Integer youwen1 = Integer.parseInt(youwen,16);

        String youya = gongneng03.substring(4,8);

        Integer youya1 = Integer.parseInt(youya,16);

        String yewei = gongneng03.substring(8,12);

        Integer yewei1 = Integer.parseInt(yewei,16);

        jsonObject.put("youwen",youwen1);
        jsonObject.put("youya",youya1);
        jsonObject.put("yewei",yewei1);


        /*String gg03 = "";

        String g1 = gongneng03.substring(6,8)+gongneng03.substring(4,6);

        Integer g11 = Integer.parseInt(g1,16);

        g1 = String.valueOf(g11);

        String shiString22 = "";*/


        /*for(int i = 0;i < g1.length();i ++)
        {
            int aaa = Integer.valueOf(g1.substring(i,i+1));

            String sss = Integer.toBinaryString(aaa);

            int q = sss.length();

            q = 4-q;

            String qianzhui = "";

            for(int zz = 0;zz < q;zz++)
            {
                shiString22 += "0";
            }

            shiString22 += sss;
        }*/



        //过去13个温度,湿度
        Page<Wendu> wenduArrays = dataService.findWenduByShebeiIdOrderByCreateTimeDesc(1, 100,shebeiId);
        List<Wendu> wenduList1 = wenduArrays.getContent();

        String[] wendus = new String[100];

        int wd = 0;

        for (Wendu wendu1 : wenduList1)
        {
            wendus[wd] = wendu1.getWendu();
            wd ++;
        }

        jsonObject.put("wenduArray",wendus);


        Page<Shidu> shiduArrays = dataService.findShiduByShebeiIdOrderByCreateTimeDesc(1, 100,shebeiId);
        List<Shidu> shiduuList1 = shiduArrays.getContent();

        String[] shidus = new String[100];

        int sd = 0;

        for (Shidu shidu1 : shiduuList1)
        {
            shidus[sd] = shidu1.getShidu();
            sd ++;
        }

        jsonObject.put("shiduArray",shidus);


        /*//坐标
        Page<Zuobiao> zuobiaoArray = dataService.findZuobiaoByShebeiIdOrderByCreateTimeDesc(1, 13,shebeiId);
        List<Zuobiao> zuobiaos = zuobiaoArray.getContent();

        Zuobiao zuobiao = zuobiaos.get(0);*/


        //过去13个震动幅度
        Page<ZhendongX> ZhendongXArrays = dataService.findZhendongXByShebeiIdOrderByCreateTimeDesc(1, 100,shebeiId);
        List<ZhendongX> zhendongXList = ZhendongXArrays.getContent();

        String[] zhendongX = new String[100];

        int zdx = 0;

        for (ZhendongX zhendongX1 : zhendongXList)
        {
            zhendongX[zdx] = zhendongX1.getX().substring(0,zhendongX1.getX().lastIndexOf(".")+2);
            zdx ++;
        }

        jsonObject.put("zhendongXArray",zhendongX);


        Page<ZhendongY> ZhendongYArrays = dataService.findZhendongYByShebeiIdOrderByCreateTimeDesc(1, 100,shebeiId);
        List<ZhendongY> zhendongYList = ZhendongYArrays.getContent();

        String[] zhendongY = new String[100];

        int zdy = 0;

        for (ZhendongY zhendongY1 : zhendongYList)
        {
            zhendongY[zdy] = zhendongY1.getY().substring(0,zhendongY1.getY().lastIndexOf(".")+2);
            zdy ++;
        }

        jsonObject.put("zhendongYArray",zhendongY);


        //数字
        String[] shuzi = new String[100];

        for(int mm = 0;mm < 100;mm++)
        {
            int nn = mm + 1;

            shuzi[mm] = String.valueOf(nn);
        }

        jsonObject.put("shuzi",shuzi);



        Page<ZhendongZ> ZhendongZArrays = dataService.findZhendongZByShebeiIdOrderByCreateTimeDesc(1, 100,shebeiId);
        List<ZhendongZ> zhendongZList = ZhendongZArrays.getContent();

        String[] zhendongZ = new String[100];

        int zdz = 0;

        for (ZhendongZ zhendongZ1 : zhendongZList)
        {
            zhendongZ[zdz] = zhendongZ1.getZ().substring(0,zhendongZ1.getZ().lastIndexOf(".")+2);
            zdz ++;
        }

        jsonObject.put("zhendongZArray",zhendongZ);


        Page<Youliang> youliangPage = dataService.findYouliangByShebeiIdOrderByCreateTimeDesc(1, 100,shebeiId);
        List<Youliang> youliangList = youliangPage.getContent();

        String[] youliangS = new String[100];

        int yl = 0;

        for (Youliang youliang : youliangList)
        {
            youliangS[yl] = youliang.getOil();
            yl ++;
        }

        jsonObject.put("youliangArray",youliangS);


//        System.out.print(jsonObject.toString());


        Shebei shebei = shebeiDao.findByShebeiId(shebeiId);

        jsonObject.put("wendufz",shebei.getWendufz());
        jsonObject.put("shidufz",shebei.getShidufz());
        jsonObject.put("xfz",shebei.getXfz());
        jsonObject.put("yfz",shebei.getYfz());
        jsonObject.put("zfz",shebei.getZfz());
        jsonObject.put("shebeiName",shebei.getShebeiName());

        String resultJson = jsonObject.toString();

        return resultJson;
    }



    /**
     * 获取并存储
     * @param request
     * @param requestBody
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/saveSocketLog", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String saveSocketLog(HttpServletRequest request, @RequestBody String requestBody) throws UnsupportedEncodingException
    {
        String requestJson = "";
        requestJson = URLDecoder.decode(requestBody, "utf-8");
        requestJson = new String(requestJson.getBytes("ISO-8859-1"),"UTF-8");
        String data = requestJson;

        System.out.print(data);


        if(data.startsWith("A1"))
        {
            data = data.substring(0,168);
        }
        else if(data.startsWith("A2"))
        {
            data = data.substring(0,120);
        }
        else if(data.startsWith("A3"))
        {
            data = data.substring(0,26);
        }
        else if(data.startsWith("A4"))
        {
            data = data.substring(0,110);
        }


        if(data.startsWith("0xA1"))
        {
            data = data.substring(2,170);
        }
        else if(data.startsWith("0xA2"))
        {
            data = data.substring(2,122);
        }
        else if(data.startsWith("0xA3"))
        {
            data = data.substring(2,28);
        }
        else if(data.startsWith("0xA4"))
        {
            data = data.substring(2,112);
        }



//        data = bin2hex(data);


//        data = "a100200029343647123334353832303138303430333037333430362e30303034302e323135393538003131362e32343336333700 04031534 282e15 742e02 7065 ae3e 06001000f800 08 1800000003 03010006ea06";

//        data = "A10030003E343647073636303031393830303130363039333433382E303030302E3030000000000000302E30000000000000000001061734002E00002E003050BA561501F7FFE6FF078300001000004706170000"


        //贞头
        String zhetou = data.substring(0,2);

        //芯片id
        String id = data.substring(2,26);


        DataInfo dataInfo = new DataInfo();

        dataInfo.setCreateTime(new Date());
        dataInfo.setDataString(data);
        dataInfo.setShebeiId(id);
        dataInfo.setStatus(0);
        dataInfo.setZhenTou(zhetou);

        dataInfoDao.save(dataInfo);
        return "ok";
    }


    public static String bin2hex(String bin) {
        char[] digital = "0123456789ABCDEF".toCharArray();
        StringBuffer sb = new StringBuffer("");
        byte[] bs = bin.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(digital[bit]);
            bit = bs[i] & 0x0f;
            sb.append(digital[bit]);
        }
        return sb.toString();
    }


    public String getJson(String urlstr) {
        org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
        HttpGet method = new HttpGet(urlstr);
        method.setHeader("Content-type" , "application/json");
        HttpResponse response = null;
        try {
            response = httpclient.execute(method);
            if (response != null) {
                // HttpEntity resEntity = response.getEntity();
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
